package com.ylx.trinasky.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylx.trinasky.constant.BaseConstant;

/**
 * 发送请求工具类
 * @author yanglixin
 */
public class SendRequestUtil {

    private static String authorization = "Bearer E-73865434-32c4-470f-a5c9-e4033bc52670";

    /**
     * 发送get请求
     * @author yangliixn
     */
    public static void sendGet(String url) {
        getToken();

        System.out.println("请求地址:" + url);
        // 创建请求并设置请求头
        HttpResponse response = HttpRequest.get(url)
                .header("Authorization", authorization)
                .execute();

        // 获取响应体
        String result = response.body();

        System.out.println("响应结果为: " + result);
    }

    /**
     * 发送post请求
     * @author yangliixn
     */
    public static void sendPost(String url, JSONObject pram) {
        getToken();

        String body = JSON.toJSONString(pram);
        System.out.println("请求地址:" + url);
        System.out.println("请求参数:" + body);

        // 创建请求并设置请求头
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", authorization)
                .body(body)
                .execute();

        // 获取响应体
        String result = response.body();
        System.out.println("响应结果为: " + result);
    }

    /**
     * 获取token
     * @author yanglixin
     */
    public static void getToken() {
        String getTokenUrl = BaseConstant.DEV_URL + "/login";
        System.out.println("获取tokenURL: " + getTokenUrl);

        JSONObject pram = new JSONObject();
        pram.put("userName","C0006520");
        pram.put("password", Base64.encode("123456"));

        String result = HttpUtil.post(getTokenUrl, JSON.toJSONString(pram));

        System.out.println("获取token响应: " + result);

        JSONObject jsonObject = JSON.parseObject(result);

        String token = jsonObject.getJSONObject("data").getString("access_token");

        System.out.println("获取的token: " + token);

        authorization = token;
    }
}
